package com.feng.yupaoback.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feng.yupaoback.common.BaseResult;
import com.feng.yupaoback.common.ErrorCode;
import com.feng.yupaoback.common.ResultUtils;
import com.feng.yupaoback.exception.BusinessException;
import com.feng.yupaoback.pojo.dto.*;
import com.feng.yupaoback.pojo.entity.Team;
import com.feng.yupaoback.pojo.entity.User;
import com.feng.yupaoback.pojo.entity.UserTeam;
import com.feng.yupaoback.pojo.vo.TeamUserVO;
import com.feng.yupaoback.service.TeamService;
import com.feng.yupaoback.service.UserService;
import com.feng.yupaoback.service.UserTeamService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/team")
public class TeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private UserTeamService userTeamService;

    /**
     * 新建团队
     * @param teamAddRequest 团队信息
     * @return 团队id
     */
    @PostMapping("/add")
    public BaseResult<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        User loginUser = userService.getCurrentUser(request);
        long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }

    /**
     * 更新队伍
     * @param teamUpdateRequest 更新信息
     * @return 更新成功
     */
    @PostMapping("/update")
    public BaseResult<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        User loginUser = userService.getCurrentUser(request);
        boolean flag = teamService.updateTeam(teamUpdateRequest, loginUser);
        if (!flag){
            throw new RuntimeException("系统异常，更新失败！");
        }
        return ResultUtils.success(true);
    }

    /**
     * 查找团队
     * @param id 团队id
     * @return 团队信息
     */
    @GetMapping("/get")
    public BaseResult<Team> getTeam(Long id) {
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数有误！");
        }
        Team team = teamService.getById(id);
        if (team == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "暂无该团队信息！");
        }
        return ResultUtils.success(team);
    }


//    /**
//     * 团队列表
//     * @param teamQueryRequest 队伍查询请求
//     * @return 队伍列表
//     */
//    @GetMapping("/list")
//    public BaseResult<List<Team>> getTeamLists(TeamQueryRequest teamQueryRequest) {
//        if (teamQueryRequest == null){
//            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
//        }
//        Team team = new Team();
//
//        // 信息更新传递
//        try {
//            BeanUtils.copyProperties(teamQueryRequest, team);
//        }catch (Exception e){
//            throw new RuntimeException("系统异常，转换失败！");
//        }
//        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
//        return ResultUtils.success(teamService.list(queryWrapper));
//    }

    /**
     * 团队列表
     * @param teamQueryRequest 队伍查询请求
     * @return 队伍列表
     */
    @GetMapping("/list")
    public BaseResult<List<TeamUserVO>> getTeamLists(TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        if (teamQueryRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        boolean isAdmin = userService.isAdmin(request);

        // 查询队伍列表
        List<TeamUserVO> teamList = teamService.getTeamList(teamQueryRequest, isAdmin);
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).toList();

        // 判断当前用户是否加入队伍
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getCurrentUser(request);
            queryWrapper.eq("userId", loginUser.getId());
            queryWrapper.in(!(CollectionUtils.isEmpty(teamIdList)),"teamId", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(queryWrapper);

            // 已加入队伍的id集合
            List<Long> hasJoinTeamIdList = userTeamList.stream().map(UserTeam::getId).toList();
            teamList.forEach(team -> {
                Boolean hasJoin = hasJoinTeamIdList.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in(!(CollectionUtils.isEmpty(teamIdList)),"teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);

    }

    /**
     * 获取我创建的队伍列表
     * @param teamQueryRequest 队伍查询请求
     * @return 队伍列表
     */
    @GetMapping("/list/my/create")
    public BaseResult<List<TeamUserVO>> getMyCreateTeamLists(TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        if (teamQueryRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        User loginUser = userService.getCurrentUser(request);
        teamQueryRequest.setUserId(loginUser.getId());

        // 由于是自己创建的，所以始终可以访问
        List<TeamUserVO> teamList = teamService.getTeamList(teamQueryRequest, true);
        if (CollectionUtils.isEmpty(teamList) || teamList.size() < 1){
            return ResultUtils.success(new ArrayList<>());
        }
        List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).toList();

        Boolean hasJoin = true;
        teamList.forEach(team -> team.setHasJoin(hasJoin));
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<UserTeam>().in("teamId", teamIdList);
        List<UserTeam> idList = userTeamService.list(queryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = idList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);
    }

    /**
     * 获取我加入的队伍列表
     * @param teamQueryRequest 队伍查询请求
     * @param request 请求
     * @return 队伍列表
     */
    @GetMapping("/list/my/join")
    public BaseResult<List<TeamUserVO>> getMyJoinTeamLists(TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        if (teamQueryRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        User loginUser = userService.getCurrentUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        if (CollectionUtils.isEmpty(userTeamList)) {
            return ResultUtils.success(new ArrayList<>());
        }
        log.info(userTeamList.toString());

        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> idList = new ArrayList<>(listMap.keySet());
        log.info(idList.toString());
        teamQueryRequest.setTeamIds(idList);

        // 由于是自己参加的，所以始终可以访问, 并且始终是加入的状态
        List<TeamUserVO> teamList = teamService.getTeamList(teamQueryRequest, true);
        Boolean hasJoin = true;
        teamList.forEach(team -> team.setHasJoin(hasJoin));
        queryWrapper = new QueryWrapper<UserTeam>().in("teamId", idList);
        List<UserTeam> teamIdList = userTeamService.list(queryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = teamIdList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);
    }


    /**
     * 团队列表（分页）
     * @param teamQueryRequest 团队查询请求
     * @return  分页信息
     */
    @GetMapping("/list/page")
    public BaseResult<Page<Team>> getTeamPages(TeamQueryRequest teamQueryRequest) {
        if (teamQueryRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQueryRequest, team);
        Page<Team> page = new Page<>(teamQueryRequest.getPageNum(), teamQueryRequest.getPageSize());
        System.out.println(teamQueryRequest.getName());
        System.out.println(teamQueryRequest.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(resultPage);
    }

    /**
     * 加入队伍
     * @param teamJoinRequest 加入请求
     * @param request 请求
     * @return 是否加入成功
     */
    @PostMapping("/join")
    public BaseResult<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        User loginUser = userService.getCurrentUser(request);
        boolean flag = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(flag);

    }

    /**
     * 退出队伍
     * @param teamQuitRequest 退出队伍请求体
     * @param request 请求
     * @return 是否退出成功
     */
    @PostMapping
    public BaseResult<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        User loginUser = userService.getCurrentUser(request);
        boolean flag = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(flag);
    }

    /**
     * 删除队伍
     * @param teamDeleteRequest 删除队伍请求体
     * @param request 请求
     * @return 是否成功删除
     */
    @PostMapping("/delete")
    public BaseResult<Boolean> deleteTeam(@RequestBody TeamDeleteRequest teamDeleteRequest, HttpServletRequest request) {
        if (teamDeleteRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
        }
        Long id = teamDeleteRequest.getId();
        if (id == null || id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除队伍的id有误");
        }
        User loginUser = userService.getCurrentUser(request);
        boolean flag = teamService.deleteTeam(id, loginUser);
        return ResultUtils.success(flag);
    }




//    @PostMapping("/list/myPage")
//    @Deprecated
//    public BaseResult<Page<Team>> getTeamList(@RequestBody TeamDisplayRequest teamDisplayRequest) {
//        if (teamDisplayRequest == null) {
//            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
//        }
//        String searchText = teamDisplayRequest.getSearchText();
//        long pageNum = teamDisplayRequest.getPageNum();
//        int status = teamDisplayRequest.getStatus();
//        System.out.println(searchText);
//        System.out.println(status);
//        System.out.println(pageNum);
//        Page<Team> page = teamService.getTeamList(searchText, pageNum, status);
//        return ResultUtils.success(page);
//    }
}
